package org.looop.studio.bean.builder.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import org.looop.studio.bean.builder.BeanBuilder;
import org.looop.studio.bean.desc.ValueDesc;
import org.looop.studio.bean.domain.BeanDefinition;
import org.looop.studio.bean.factory.BeanFactory;
import org.looop.studio.bean.util.BeanUtil;

public class SetterBuilder implements BeanBuilder {
	private ConstructorBuilder constructorBuilder = new ConstructorBuilder();
	@Override
	public Object buildBean(BeanFactory beanFactory,
			BeanDefinition beanDefinition) throws InstantiationException,
			IllegalAccessException, ClassNotFoundException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException {
		Object bean = constructorBuilder.buildBean(beanFactory, beanDefinition);
		if (beanDefinition.getProperties() != null) {
			Map<String, Object> properties = new HashMap<String, Object>();
			for (Map.Entry<String, ValueDesc> entry : beanDefinition
					.getProperties().entrySet()) {
				String key = entry.getKey();
				Object value = entry.getValue().getValue(beanFactory);
				properties.put(key, value);
			}
			for (Map.Entry<String, Object> entry : properties.entrySet()) {
				BeanUtil.setBeanProperty(bean, entry.getKey(), entry.getValue());
			}
		}
		return bean;
	}

}
